/*
 * @Author: sean_kei@163.com
 * @Date: 2021-06-08 15:07:55
 * @LastEditors: sean_kei@163.com
 * @LastEditTime: 2022-08-04 14:15:26
 */
package com.wxhandle.cleandemo.sso.controller;


import java.util.List;

import com.wxhandle.cleandemo.application.dto.identity.SysUserDto;
import com.wxhandle.cleandemo.core.command.identity.RegisterUserCommand;
import com.wxhandle.cleandemo.core.domain.identity.SysUser;
import com.wxhandle.cleandemo.core.services.SysUserService;

import org.modelmapper.ModelMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@RestController
@RequestMapping("sysuser")
public class SysUserController {

    private final SysUserService userService;
    private final ModelMapper modelMapper;

    @GetMapping("{id}")
    SysUser getOne(@PathVariable("id") String id){
        return userService.getOneByLogin(id);
    }

    @GetMapping
    List<SysUser> getList() {
        return userService.getList(null);
    }

    @PostMapping(consumes="application/json")
    SysUser registerUser(@RequestBody RegisterUserCommand command){
        return userService.register(command);
    }

    @GetMapping("myinfo")
    SysUserDto getMyInfo(@AuthenticationPrincipal Jwt jwt) {
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        Object pri = auth.getPrincipal();
        String subject = jwt.getSubject();
        return modelMapper.map((SysUser)auth.getPrincipal(), SysUserDto.class);
    }

}
